import React, { useState } from 'react';
import { Text, View, TouchableOpacity, TextInput, ToastAndroid, Linking } from 'react-native';
import { login } from '../api/user';
import { useAuth } from "../context/AuthProvider";

const Login = ({navigation}) => {
	const { setUser } = useAuth();
	const [userName,setUserName] = useState('');
  	const [password,setPassword] = useState('');

	const toLogin = (userName,password) => {
		let data = {userName:userName,password:password}

		login(data).then(res => {
			if(res.code === '200') {
				ToastAndroid.show(res.msg,ToastAndroid.SHORT,ToastAndroid.TOP)
				setUser(res.data)
				navigation.navigate('TabBar')
			}
			if(res.code === '500') {
				ToastAndroid.show(`登录失败！${res.msg}`,ToastAndroid.SHORT,ToastAndroid.TOP)
			}
		})
	}
	
	return (
		<View style={{ flex:1,alignItems:'center',justifyContent:'center'}} >
			<Text style={{fontSize:24}}>用户登录</Text>
			<View style={{alignItems:'center',justifyContent:'center'}}>
				<TextInput style={{
					width:300,
					height:50,
					margin:30,
					padding:10,
					borderColor:'#777',
					borderWidth:1,
					borderRadius:10
					}} 
					clearTextOnFocus={true}
					placeholder={'手机号/用户名/邮箱'}
					onChangeText={text => setUserName(text)}
				/>

				<TextInput style={{
					width:300,
					height:50,
					marginBottom:20,
					padding:10,
					borderColor:'#777',
					borderWidth:1,
					borderRadius:10
					}} 
					clearTextOnFocus={true}
					placeholder={'密码'}
					secureTextEntry={true}
					onChangeText={text => setPassword(text)}
				/>

				<View style={{flexDirection:'row',alignItems:'center',marginBottom:10}}>
					<Text style={{color:'blue',marginLeft:240}} onPress={() => Linking.openURL('#')}>忘记密码？</Text>
				</View>

				<TouchableOpacity
					style={{
						width:300,
						height:50,
						borderRadius:10,
						backgroundColor:'#0099ff',
						alignItems:'center',
						justifyContent:'center'
					}}
					onPress={() => toLogin(userName,password)}
				>
					<Text style={{color:'#fff'}}>登录</Text>
				</TouchableOpacity>
			</View>
		</View>
	);
}

export default Login;